//
//  zcVideoViewController.m
//  智能控制系统
//
//  Created by Rankin on 15/12/2.
//
//
#define BUT_STATE_PLAY 1
#define BUT_STATE_PAUSE 0
#define BUT_STATE_SLIENCE 0
#define BUT_STATE_SOUND 1
#define BUT_VOICE_UP 1
#define BUT_VOICE_DOWN 0

#define GZCZ_DISPATCH_ASYNC_BACK(block) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block)
#define GZCZ_DISPATCH_ASYNC_MAIN(block) dispatch_async(dispatch_get_main_queue(),block)
//释放内存
#if __has_feature(objc_arc)
#define GZCZ_STRONG strong
#define HK_OBJECT_NULL(__POINTER) { if(__POINTER) { __POINTER = nil; } }
#define HK_TIMER_NULL(__TIMER) { if(__TIMER) { [__TIMER invalidate]; __TIMER = nil; } }
#else
#define GZCZ_STRONG retain
#define HK_OBJECT_NULL(__POINTER) { if(__POINTER) { [__POINTER release];__POINTER = nil; } }
#define HK_TIMER_NULL(__TIMER) { if(__TIMER) { [__TIMER invalidate]; [__TIMER release]; __TIMER = nil; } }
#endif

#import "zcVideoViewController.h"


#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <MediaPlayer/MediaPlayer.h>

@interface zcVideoViewController()<HKPlayerDelegate>

@end

@implementation zcVideoViewController
MPVolumeView *volumeView;
NSTimer *volumeHoldTimer;
- (id)initWithNibName:(NSString*)nibNameOrNil bundle:(NSBundle*)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Uncomment to override the CDVCommandDelegateImpl used
        // _commandDelegate = [[MainCommandDelegate alloc] initWithViewController:self];
        // Uncomment to override the CDVCommandQueue used
        // _commandQueue = [[MainCommandQueue alloc] initWithViewController:self];
    }
    return self;
}

- (id)init
{
    self = [super init];
    if (self) {
        // Uncomment to override the CDVCommandDelegateImpl used
        // _commandDelegate = [[MainCommandDelegate alloc] initWithViewController:self];
        // Uncomment to override the CDVCommandQueue used
        // _commandQueue = [[MainCommandQueue alloc] initWithViewController:self];
    }
    return self;
}

- (id)initWithUmid:(NSString*)umid deviceUserId:(NSString*)deviceUserId devicePassword:(NSString*)pwd channelNo:(int)channelNo{
    self = [self initWithNibName:@"VideoPlayView" bundle:[NSBundle mainBundle]];
    if(self){
        self.P2PServe = @"app.umeye.cn";
        self.serverPort = 8300;
        self.deviceUMID = umid;
        self.deviceUserID = deviceUserId;
        self.devicePassword = pwd;
        self.channelNo = channelNo;
        volumeView = [[MPVolumeView alloc] init];
    }
    return self;
}

#pragma mark View lifecycle

- (void)viewWillAppear:(BOOL)animated
{
    // View defaults to full size.  If you want to customize the view's size, or its subviews (e.g. webView),
    // you can do so here.
    
    [super viewWillAppear:animated];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onResume) name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onPause) name:UIApplicationDidEnterBackgroundNotification object:nil];
    
    
     self.PlayerTitle.text = self.deviceUMID;
    
    self.playerClient = [[HKSDeviceClient alloc]init];//初始化播放器
    [self.playerClient.view setFrame:CGRectMake(0,0,self.videoDisplayView.frame.size.width,self.videoDisplayView.frame.size.height)];
    self.playerClient.view.layer.borderWidth = 0;
    self.playerClient.audioEnabled = YES;
    self.playerClient.view.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin
    | UIViewAutoresizingFlexibleRightMargin
    | UIViewAutoresizingFlexibleTopMargin
    | UIViewAutoresizingFlexibleBottomMargin
    | UIViewAutoresizingFlexibleHeight
    | UIViewAutoresizingFlexibleWidth;
    [self.playerClient setDisplayViewColor:[UIColor redColor]];
    
    [self.videoDisplayView addSubview :self.playerClient.view];
    self.playerClient.delegate = self;

    
    //绑定事件
    [self.backBut addTarget:self action:@selector(PopToBack:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.playBut setTag:BUT_STATE_PLAY];
    [self.playBut setImage:[UIImage imageNamed:@"video_stop"] forState:UIControlStateSelected];
    [self.playBut addTarget:self action:@selector(onPlayAction:) forControlEvents:UIControlEventTouchUpInside];
    //     [self.voiceBut addTarget:self action:@selector(onPlayAction::) forControlEvents:UIControlEventTouchUpInside];
    
    [self.rightBut setTag:HKS_NPC_D_MON_PTZ_CMD_PAN_RIGHT];
  
//    [self.rightBut setImage:[UIImage imageNamed:@"btn_right_1"] forState:UIControlStateHighlighted];
    [self.rightBut addTarget:self action:@selector(onPtzAction:) forControlEvents:UIControlEventTouchDown];
    [self.rightBut addTarget:self action:@selector(onPtzStopAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.rightBut addTarget:self action:@selector(onPtzStopAction:) forControlEvents:UIControlEventTouchDragExit];
    [self.rightBut addTarget:self action:@selector(onPtzStopAction:) forControlEvents:UIControlEventTouchUpOutside];
    
    [self.leftBut setTag:HKS_NPC_D_MON_PTZ_CMD_PAN_LEFT];
//    [self.leftBut setImage:[UIImage imageNamed:@"btn_left_1"] forState:UIControlStateHighlighted];
    [self.leftBut addTarget:self action:@selector(onPtzAction:) forControlEvents:UIControlEventTouchDown];
    [self.leftBut addTarget:self action:@selector(onPtzStopAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.leftBut addTarget:self action:@selector(onPtzStopAction:) forControlEvents:UIControlEventTouchDragExit];
    [self.leftBut addTarget:self action:@selector(onPtzStopAction:) forControlEvents:UIControlEventTouchUpOutside];
    
    [self.upBut setTag:HKS_NPC_D_MON_PTZ_CMD_TILT_UP];
//    [self.upBut setImage:[UIImage imageNamed:@"btn_up_1"] forState:UIControlStateHighlighted];
    [self.upBut addTarget:self action:@selector(onPtzAction:) forControlEvents:UIControlEventTouchDown];
    [self.upBut addTarget:self action:@selector(onPtzStopAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.upBut addTarget:self action:@selector(onPtzStopAction:) forControlEvents:UIControlEventTouchDragExit];
    [self.upBut addTarget:self action:@selector(onPtzStopAction:) forControlEvents:UIControlEventTouchUpOutside];
    
    [self.downBut setTag:HKS_NPC_D_MON_PTZ_CMD_TILT_DOWN];
//    [self.downBut setImage:[UIImage imageNamed:@"btn_down_1"] forState:UIControlStateHighlighted];
    [self.downBut addTarget:self action:@selector(onPtzAction:) forControlEvents:UIControlEventTouchDown];
    [self.downBut addTarget:self action:@selector(onPtzStopAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.downBut addTarget:self action:@selector(onPtzStopAction:) forControlEvents:UIControlEventTouchDragExit];
    [self.downBut addTarget:self action:@selector(onPtzStopAction:) forControlEvents:UIControlEventTouchUpOutside];
    
    
    [self.lesSenBut setTag:HKS_NPC_D_MON_PTZ_CMD_ZOOM_IN];
    [self.lesSenBut  addTarget:self action:@selector(onPtzAction:) forControlEvents:UIControlEventTouchDown];
    [self.lesSenBut addTarget:self action:@selector(onPtzStopAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.lesSenBut addTarget:self action:@selector(onPtzStopAction:) forControlEvents:UIControlEventTouchDragExit];
    [self.lesSenBut addTarget:self action:@selector(onPtzStopAction:) forControlEvents:UIControlEventTouchUpOutside];
    
    [self.lesSenBut setTag:HKS_NPC_D_MON_PTZ_CMD_ZOOM_OUT];
    [self.lesSenBut  addTarget:self action:@selector(onPtzAction:) forControlEvents:UIControlEventTouchDown];
    [self.lesSenBut addTarget:self action:@selector(onPtzStopAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.lesSenBut addTarget:self action:@selector(onPtzStopAction:) forControlEvents:UIControlEventTouchDragExit];
    [self.lesSenBut addTarget:self action:@selector(onPtzStopAction:) forControlEvents:UIControlEventTouchUpOutside];
    
    [self.voiceBut setTag:BUT_STATE_SLIENCE];
    [self.voiceBut setBackgroundImage:[UIImage imageNamed:@"playview_cloud_sound_h"] forState:UIControlStateSelected];
    [self.voiceBut addTarget:self action:@selector(onSoundOpen:) forControlEvents:UIControlEventTouchUpInside];

    
    [self.audioBut addTarget:self action:@selector(onRECAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.voiceUp setTag:BUT_VOICE_UP];
    [self.voiceUp addTarget:self action:@selector(onVoiceChange:) forControlEvents:UIControlEventTouchDown];
    [self.voiceUp addTarget:self action:@selector(onVoiceChangeStop:) forControlEvents:UIControlEventTouchUpInside];
    [self.voiceUp addTarget:self action:@selector(onVoiceChangeStop:) forControlEvents:UIControlEventTouchUpOutside];
    
    
    [self.voiceDown setTag:BUT_VOICE_DOWN];
    [self.voiceDown addTarget:self action:@selector(onVoiceChange:) forControlEvents:UIControlEventTouchDown];
    [self.voiceDown addTarget:self action:@selector(onVoiceChangeStop:) forControlEvents:UIControlEventTouchUpInside];
    [self.voiceDown addTarget:self action:@selector(onVoiceChangeStop:) forControlEvents:UIControlEventTouchUpOutside];
    
    [self.savePhotoBut addTarget:self action:@selector(onPtotoAction:) forControlEvents:UIControlEventTouchDown];
    
    [self.fullscreenBut addTarget:self action:@selector(onFullScreen:) forControlEvents:UIControlEventTouchDown];
    
    [self.rotateBut addTarget:self action:@selector(onRotate:) forControlEvents:UIControlEventTouchDown];
    
//    HKSDeviceCodecItem *codecItem = [[HKSDeviceCodecItem alloc] init];
//    codecItem.iChNo = self.playerClient.deviceChannel;
//    if ([self.playerClient deviceCodecInfo:codecItem] == HKS_NPC_D_MPI_MON_ERROR_SUC) {
//        if (codecItem.pVideoFormat.iResolution == HKS_NPC_D_MON_VEDIO_RESOLUTION_QCIF
//            || codecItem.pVideoFormat.iFrameRate < 7) {
//            codecItem.pVideoFormat.iResolution = HKS_NPC_D_MON_VEDIO_RESOLUTION_QVGA;
//            codecItem.pVideoFormat.iFrameRate = 7;
//            [self.playerClient setDeviceCodecInfo:codecItem];
//        }
//        
//    }
    
    
    //添加手势 右滑后退
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(handleBackRecognizer:)];
    [self.view addGestureRecognizer:swipe];
}

-(void)viewDidDisappear:(BOOL)animated{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
}

-(void)handleBackRecognizer:(UISwipeGestureRecognizer*)recognizer{
    if(recognizer.direction==UISwipeGestureRecognizerDirectionRight){
        NSLog(@"右划后退手势");
        [self PopToBack:nil];
    }
}



#pragma 视频控制的方法
-(void)play{
    [self showLoading];
    [self.playerClient setDeviceConnParam:self.P2PServe
                               serverPort:self.serverPort
                               deviceUMID: self.deviceUMID
                             deviceUserID:self.deviceUserID
                           devicePassword:self.devicePassword
                            deviceChannel:self.channelNo
                             deviceStream:1
                             deviceVendor:-1];
    
    NSLog(@"tap");
    NSLog(@"%d:%d:%f",[self.playerClient playerState],[self.playerClient videoFrameRate],[self.playerClient videoNetworkSpeed]);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self.playerClient stop:YES exit:YES];
        NSLog(@"%d:%d:%f",[self.playerClient playerState],[self.playerClient videoFrameRate],[self.playerClient videoNetworkSpeed]);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.playerClient start];
            NSLog(@"%d:%d:%f",[self.playerClient playerState],[self.playerClient videoFrameRate],[self.playerClient videoNetworkSpeed]);
            [self dismissLoading];
        });
    });
    
    if (_playStatusCheckTimer) {
        [_playStatusCheckTimer invalidate];
        _playStatusCheckTimer =nil;
    }
    _playStatusCheckTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateLivePlayStatus) userInfo:nil repeats:YES];
    
}

-(void)onRotate:(id)sender{
    UIButton* select = (UIButton*)sender;
    CGAffineTransform rotate;
    NSLog(@"rotate 180");
    [select setSelected:!select.isSelected];
    if(select.isSelected){
        rotate = CGAffineTransformMakeRotation(M_PI);
        [self.videoDisplayView setTransform:rotate];
    }
    else{
        rotate = CGAffineTransformMakeRotation(2*M_PI);
    }
    [self.videoDisplayView setTransform:rotate];
}

-(void)PopToBack:(id)sender{
    
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (orientation!=UIInterfaceOrientationPortrait) {
        [[UIDevice currentDevice]setValue:[NSNumber numberWithInt: UIInterfaceOrientationPortrait] forKey:@"orientation"];
        return;
    }
    
    
//    [self.navigationController popToRootViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:^{
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //退出释放对象
            [self.playerClient stop:YES exit:YES];
            [_playStatusCheckTimer invalidate];
            _playStatusCheckTimer = nil;
        });
    }];
}

-(void)print{
    NSLog(@"state:%d,rate:%d,speed:%f",[self.playerClient playerState],[self.playerClient videoFrameRate],[self.playerClient videoNetworkSpeed]);
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.searchDevices = [NSMutableArray array];
    //    [self starSearchDevice];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)stop{
    if (_playerClient) {
        [_playerClient stop:YES];
    }
}

#pragma mark - Button Action
- (void)onPlayAction:(id)sender{
    UIButton* select = (UIButton*)sender;
    [select setSelected:!select.isSelected];
    if(select.isSelected){
        [self play];
    }else{
        [self stop];
    }
    
}

//增加减小音量，1增加，0减少
- (void)changeVoiceInternval:(NSInteger)director{
 
    UISlider* volumeViewSlider = nil;
    for (UIView *view in [volumeView subviews]){
        if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
            volumeViewSlider = (UISlider*)view;
            break;
        }
    }
    
    // retrieve system volume
    float systemVolume = volumeViewSlider.value;
    
    if(director==BUT_VOICE_DOWN){
        // change system volume, the value is between 0.0f and 1.0f
        [volumeViewSlider setValue:systemVolume-1.0f/16 animated:NO];
    }else{
        [volumeViewSlider setValue:systemVolume+1.0f/16 animated:NO];
    }
    
    // send UI control event to make the change effect right now.
    [volumeViewSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
    
}

- (void)onStopAction:(id)sender{
    [self stop];
}

-(void)onVoiceChange:(id)sender{
    UIButton *but = (UIButton*)sender;
    if(but.tag == BUT_VOICE_DOWN){
        [self changeVoiceInternval:but.tag];
    }else{
        [self changeVoiceInternval:but.tag];
    }
    //todo 加入长按的交互
//   volumeHoldTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateLivePlayStatus) userInfo:nil repeats:YES];
}

-(void)onVoiceChangeStop:(id)sender{
    UIButton *but = (UIButton*)sender;
//    [volumeHoldTimer invalidate];
//    volumeHoldTimer = nil;
}

- (void)onPtotoAction:(id)sender{
    if (_playerClient && _playerClient.playerState == HKS_NPC_D_MON_DEV_PLAY_STATUS_PLAYING) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"IMG"];
        
        //删除文件夹内的文件
        NSFileManager* fm = [[NSFileManager alloc]init];
        [fm removeItemAtPath:path error:nil];
        
        //生成新的截图文件
        [_playerClient savePhotosToPath:path];
        
        //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC*3),
        //                       dispatch_get_main_queue(), ^{
        
        NSArray* parr = [fm contentsOfDirectoryAtPath:path error:nil];
        
        UIImage* photo = [UIImage imageWithContentsOfFile:
                          [path stringByAppendingPathComponent:
                           [parr lastObject]]];
        if (photo==nil) {
            [self showMessage:@"截图失败,可能是您的存储空间不足"];
        }
        else{
            UIImageWriteToSavedPhotosAlbum(photo, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
        }
        //        });
    }
}

- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (!error) {
        [self showMessage:@"截图成功,截图已保存到您的相册中"];
    }else {
        [self showMessage:@"截图失败,可能是您的存储空间不足"];
    }
}

- (void)onFullScreen:(id)sender{
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
//    NSNumber *v = [[UIDevice currentDevice]valueForKey:@"orientation"];
}

- (void)onRECAction:(id)sender{
    if (_playerClient && _playerClient.playerState == HKS_NPC_D_MON_DEV_PLAY_STATUS_PLAYING) {
        if (_playerClient.recordEnabled) {
            
            [_playerClient stopRecordToPath];
            [self showMessage:@"录像结束..."];
        }else{
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *mp4Name = [dateFormatter stringFromDate:[NSDate date]];
            NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"Mp4//%@.mp4",mp4Name]];
            [_playerClient startRecordToPath:path];
            [self showMessage:@"开始录像..."];
        }
    }
}



- (void)onTalkbackAction:(id)sender{
    if (_playerClient && _playerClient.playerState == HKS_NPC_D_MON_DEV_PLAY_STATUS_PLAYING) {
        if (_playerClient.talkState) {
            [_playerClient stopPPTTalk];
            _playerClient.audioEnabled = YES;//open sound
        }else{
            _playerClient.audioEnabled = NO;//close sound
            [_playerClient startPPTTalkWithType:HKS_NPC_D_AUDIO_PCM];
        }
    }
}

- (void)onSoundOpen:(id)sender{
    UIButton* select = (UIButton*)sender;
        if (_playerClient && _playerClient.playerState == HKS_NPC_D_MON_DEV_PLAY_STATUS_PLAYING) {
            [select setSelected:!select.isSelected];
            if (select.selected) {
                _playerClient.audioEnabled = NO;//open sound
            }else {
                _playerClient.audioEnabled = YES;//close sound
                
            }
        }
//    });
    
}

//云台控制
- (void)onPtzAction:(id)sender{
    UIButton *clickedBut = (UIButton*)sender;
    
    if (_playerClient && _playerClient.playerState == HKS_NPC_D_MON_DEV_PLAY_STATUS_PLAYING) {
        [_playerClient ptzControlWithCmd:clickedBut.tag data:3];
    }
}
- (void)onPtzStopAction:(id)sender{
    
    if (_playerClient && _playerClient.playerState == HKS_NPC_D_MON_DEV_PLAY_STATUS_PLAYING) {
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [_playerClient ptzControlWithCmd:HKS_NPC_D_MON_PTZ_CMD_STOP data:3];
        });
    }
}



#pragma 播放状态检测 的方法
- (void)updateLivePlayStatus{
    if (_playerClient) {
        int status = _playerClient.playerState;
        NSString *statusStr;
        if (status == HKS_NPC_D_MON_DEV_PLAY_STATUS_PLAYING) {


            if(self.playBut.tag != BUT_STATE_PLAY){
                [self.playBut setBackgroundImage:[UIImage imageNamed:@"pause_114"] forState:UIControlStateNormal];
                self.playBut.tag = BUT_STATE_PAUSE;
                
            }
            statusStr = @"正在播放";
        }
        else if(status == HKS_NPC_D_MON_DEV_PLAY_STATUS_STOP){
            if(self.playBut.tag != BUT_STATE_PAUSE){
                [self.playBut setBackgroundImage:[UIImage imageNamed:@"play_114"] forState:UIControlStateNormal];
                self.playBut.tag = BUT_STATE_PLAY;
                
            }
            statusStr = @"已停止";
        }
        else if(status == HKS_NPC_D_MON_DEV_PLAY_STATUS_CONNECT_SERVER){
            statusStr = @"正在连接...";
        }
        else if(status == HKS_NPC_D_MON_DEV_PLAY_STATUS_CONNECT_SUCESS){
            statusStr = @"缓冲中...";
        }
        else if(status == HKS_NPC_D_MON_DEV_PLAY_STATUS_CONNECT_FAIL){
            if(self.playBut.tag != BUT_STATE_PAUSE){
                [self.playBut setBackgroundImage:[UIImage imageNamed:@"play_114"] forState:UIControlStateNormal];
                self.playBut.tag = BUT_STATE_PLAY;
                
            }
            statusStr = @"连接失败";
        }else if(status == HKS_NPC_D_MON_DEV_PLAY_STATUS_READY){
            
            statusStr = @"播放器就绪";
        }
        else if(status == HKS_NPC_D_MON_DEV_PLAY_STATUS_LOGIN_ERROR_PASSWORD
                || status == HKS_NPC_D_MON_DEV_PLAY_STATUS_LOGIN_ERROR_USER)
        {
            statusStr = @"登录失败";
        }
        else{
            //其他的请到HKSDeviceState.h 里面找出HKS_NPC_D_MON_DEV_PLAY_STATUS_*定义，这里就不全部列举了
            statusStr = @"发生错误";
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *display =[[NSString alloc]initWithFormat:@"帧率:%dfps,网络:%dkbps",
                                [self.playerClient videoFrameRate],(int)[self.playerClient videoNetworkSpeed]];
            
            [self.playStateText setText: statusStr];
            
            
            [self.playSpeedText setText:display];
            
        });
        
    }
}


#pragma loading 和 toast 的方法
-(void)showMessage:(NSString *)message
{
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    UIView *showview =  [[UIView alloc]init];
    showview.backgroundColor = [UIColor grayColor];
    showview.frame = CGRectMake(1, 1, 1, 1);
    showview.alpha = 1.0f;
    showview.layer.cornerRadius = 5.0f;
    showview.layer.masksToBounds = YES;
    [window addSubview:showview];
    
    UILabel *label = [[UILabel alloc]init];
    CGSize LabelSize = [message sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(290, 9000)];
    label.frame = CGRectMake(10, 5, LabelSize.width, LabelSize.height);
    label.text = message;
    label.textColor = [UIColor whiteColor];
    label.textAlignment = 1;
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:15];
    [showview addSubview:label];
    
    showview.frame = CGRectMake(( self.view.frame.size.width  - LabelSize.width - 20)/2, self.view.frame.size.height - 200, LabelSize.width+20, LabelSize.height+10);
    [UIView animateWithDuration:2.5 animations:^{
        showview.alpha = 0;
    } completion:^(BOOL finished) {
        [showview removeFromSuperview];
    }];
}

- (void)showLoading{
    self.loadingView = [[UIActivityIndicatorView alloc]init];
    self.loadingView.frame =CGRectMake(self.videoDisplayView.frame.size.width/2-18,self.videoDisplayView.frame.size.height/2,36,36);
    //    [self.loadingView setCenter:CGPointMake(self.view.frame.size.width/2 - 100, self.view.frame.size.height-250)];
    [self.loadingView setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
    
    [self.view addSubview:self.loadingView];
    [self.loadingView startAnimating];
}

-(void)dismissLoading{
    [self.loadingView stopAnimating];
    [self.loadingView removeFromSuperview];
}


- (void)onPause
{
    [self stop];
}

- (void)onResume
{
    [self play];
}
@end
